package com.yang.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.yang.domain.dto.UserDTO;
import com.yang.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.yang.constants.RedisConstants.LOGIN_USER_KEY;
import static com.yang.constants.RedisConstants.LOGIN_USER_TTL;

/**
 * <p>
 *  第一个登录拦截器：
 *  作用获取token，查询redis用户，存放到userHolder
 *  并且刷新token的有效期
 * </p>
 *
 * @author yang
 * @since 2022-10-22
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头里面获取token，并校验
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)){
            return true;
        }
        //2.基于token从redis里面获取到用户
        String key  = LOGIN_USER_KEY + token;
        Map<Object, Object> userDtoMap = stringRedisTemplate.opsForHash().entries(key);

        //3.判断用户是否存在
        if (userDtoMap.isEmpty()){
            //4.不存在，直接放行，交给第二个拦截器去拦截
            return true;
        }

        //5.存在，将查询到的hash数据转为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userDtoMap, new UserDTO(), false);

        //6.存入到ThreadLocal，刷新token有效期
        UserHolder.saveUser(userDTO);

        stringRedisTemplate.expire(key,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}